package enterprise.manage.security.impl;

import enterprise.manage.dao.UserDao;
import enterprise.manage.entity.User;
import enterprise.manage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException; 

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: zhenmingyue
 * Date: 2011-7-1 17:25:50
 * Desc:
 * For :
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;

    /**
     * 获取用户Details信息的回调函数.
     */
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {

        User user = userDao.getByUserName(userName);
        if (user == null) {
            throw new UsernameNotFoundException("用户" + userName + " 不存在");
        }

        GrantedAuthority[] grantedAuths = obtainGrantedAuthorities(user);

        //-- mini-web示例中无以下属性, 暂时全部设为true. --//

        boolean enabled = false;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
        if(user.getEnable() == 1){
           enabled = true;
        }
        UserDetails userdetails = new org.springframework.security.userdetails.User(user.getUserName(), user
                .getPsw(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

        return userdetails;
    }

    /**
     * 获得用户所有角色的权限集合.
     */
    private GrantedAuthority[] obtainGrantedAuthorities(User user) {
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
        List<String> authorityNames = userService.queryUserAuthorityNames(user.getId());
        for (String authorityName :authorityNames) {
            authSet.add(new GrantedAuthorityImpl(authorityName));
        }
        return authSet.toArray(new GrantedAuthority[authSet.size()]);
    }
}
